

package com.maoshi.shop.distribution.platform.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.maoshi.shop.bean.enums.OfflineHandleEventType;
import com.maoshi.shop.bean.model.OfflineHandleEvent;
import com.maoshi.shop.bean.param.OfflineHandleEventAuditParam;
import com.maoshi.shop.common.config.Constant;
import com.maoshi.shop.common.exception.MaoshiShopBindException;
import com.maoshi.shop.common.util.PageParam;
import com.maoshi.shop.distribution.comment.model.DistributionProd;
import com.maoshi.shop.distribution.comment.service.DistributionProdService;
import com.maoshi.shop.security.platform.model.MaoshiSysUser;
import com.maoshi.shop.security.platform.util.SecurityUtils;
import com.maoshi.shop.security.comment.exception.UnauthorizedException;
import com.maoshi.shop.service.OfflineHandleEventService;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author lgh on 2019/04/01.
 */
@RestController
@RequestMapping("/platform/distributionProd")
@AllArgsConstructor
public class DistributionProdController {

    private final DistributionProdService distributionProdService;

    private final OfflineHandleEventService offlineHandleEventService;

    @GetMapping("/count")
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:info')")
    public ResponseEntity<Integer> count(Long prodId) {
        return ResponseEntity.ok(distributionProdService.count(new LambdaQueryWrapper<DistributionProd>()
                .eq(DistributionProd::getProdId, prodId)));
    }

    /**
     * 分页获取
     */
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:page')")
    public ResponseEntity<IPage<DistributionProd>> page(DistributionProd distributionProd, PageParam<DistributionProd> page, String prodName, Integer state) {
        distributionProd.setState(state);
        IPage<DistributionProd> list = distributionProdService.distributionProdsPage(page, distributionProd, prodName);
        return ResponseEntity.ok(list);
    }

    /**
     * 获取信息
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:info')")
    public ResponseEntity<DistributionProd> info(@PathVariable("id") Long id) {
        DistributionProd distributionProd = distributionProdService.getById(id);
        return ResponseEntity.ok(distributionProd);
    }

    /**
     * 保存
     */
    @PostMapping
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:save')")
    public ResponseEntity<Void> save(@RequestBody @Valid DistributionProd distributionProd) {
        distributionProd.setShopId(Constant.PLATFORM_SHOP_ID);
        distributionProd.setModifier(SecurityUtils.getSysUser().getUserId());
        setDefaultAwardNumbers(distributionProd);
        distributionProdService.save(distributionProd);

        distributionProdService.removeDistributionProdPOCacheByProdId(distributionProd.getProdId());
        return ResponseEntity.ok().build();
    }


    /**
     * 修改
     */
    @PutMapping
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:update')")
    public ResponseEntity<Void> update(@RequestBody @Valid DistributionProd distributionProd) {
        MaoshiSysUser sysUser = SecurityUtils.getSysUser();

        if (!Objects.equals(distributionProd.getShopId(), Constant.PLATFORM_SHOP_ID)) {
            throw new UnauthorizedException("未授权");
        }
        distributionProd.setModifier(sysUser.getUserId());
        setDefaultAwardNumbers(distributionProd);
        distributionProdService.updateById(distributionProd);
        distributionProdService.removeDistributionProdPOCacheByProdId(distributionProd.getProdId());
        return ResponseEntity.ok().build();
    }

    /**
     * 删除
     */
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:delete')")
    public ResponseEntity<Void> delete(@RequestBody List<Long> ids) {
        distributionProdService.removeByIds(ids);
        return ResponseEntity.ok().build();
    }


    private void setDefaultAwardNumbers(@Valid @RequestBody DistributionProd distributionProd) {
        distributionProd.setUpdateTime(new Date());

        if (StrUtil.isBlank(distributionProd.getParentAwardNumbers())) {
            // 固定奖励
            if (Objects.equals(distributionProd.getAwardNumberSet(), 0)) {
                distributionProd.setParentAwardNumbers("0");
            } else {
                distributionProd.setParentAwardNumbers(null);
            }
        }
        if (StrUtil.isBlank(distributionProd.getAwardNumbers())) {
            distributionProd.setAwardNumbers("0");
            // 固定奖励
            if (Objects.equals(distributionProd.getAwardNumberSet(), 0)) {
                distributionProd.setAwardNumbers("0");
            } else {
                distributionProd.setAwardNumbers(null);
            }
        }
    }

    /**
     * 通过活动id获取下线信息
     */
    @GetMapping("/getOfflineEventByDistProdId/{distributionProdId}")
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:info')")
    public ResponseEntity<OfflineHandleEvent> getOfflineEventByDistProdId(@PathVariable("distributionProdId") Long distributionProdId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.DISTRIBUTION_PROD.getValue(), distributionProdId);
        return ResponseEntity.ok(offlineHandleEvent);
    }

    /**
     * 下线活动
     */
    @PostMapping("/offline")
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:update')")
    public ResponseEntity<Void> offline(@RequestBody OfflineHandleEvent offlineHandleEvent) {
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        DistributionProd distributionProd = distributionProdService.getById(offlineHandleEvent.getHandleId());
        if (distributionProd == null) {
            throw new MaoshiShopBindException("未找到分销商品信息");
        }
        distributionProdService.offline(distributionProd, offlineHandleEvent.getOfflineReason(), sysUserId);
        return ResponseEntity.ok().build();
    }

    /**
     * 审核活动
     */
    @PostMapping("/auditDistributionProd")
    @PreAuthorize("@pms.hasPermission('platform:distributionProd:update')")
    public ResponseEntity<Void> auditDistributionProd(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        DistributionProd distributionProd = distributionProdService.getById(offlineHandleEventAuditParam.getHandleId());
        if (distributionProd == null) {
            throw new MaoshiShopBindException("未找到该分销商品信息");
        }
        distributionProdService.auditDistributionProd(offlineHandleEventAuditParam, sysUserId);

        return ResponseEntity.ok().build();
    }
}
